package com.ruoyi.supermarket.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.AuditStatusType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.supermarket.bean.ProductDetail;
import com.ruoyi.supermarket.domain.Product;
import com.ruoyi.supermarket.domain.ProductAttribute;
import com.ruoyi.supermarket.domain.ProductSku;
import com.ruoyi.supermarket.domain.Shop;
import com.ruoyi.supermarket.mapper.ProductAttributeMapper;
import com.ruoyi.supermarket.mapper.ProductMapper;
import com.ruoyi.supermarket.mapper.ProductSkuMapper;
import com.ruoyi.supermarket.mapper.ShopMapper;
import com.ruoyi.supermarket.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 * 
 * @author 李其伟
 * @date 2023-08-11
 */
@Service
public class ProductServiceImpl implements ProductService
{
    private static AtomicInteger atomicNum = new AtomicInteger();

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductAttributeMapper productAttributeMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ShopMapper shopMapper;
    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ProductDetail selectProductById(Long id)
    {
        ProductDetail pd = new ProductDetail();
        Product p = productMapper.selectProductById(id);
        pd.setProduct(p);

        //商品规格表
        ProductAttribute productAttribute = new ProductAttribute();
        productAttribute.setSku(p.getSku());
        List<ProductAttribute> productAttributeList = productAttributeMapper.selectProductAttributeList(productAttribute);
        pd.setProductAttributeList(productAttributeList);

        //商品sku表
        ProductSku productSku = new ProductSku();
        productSku.setSku(p.getSku());
        List<ProductSku> productSkuList = productSkuMapper.selectProductSkuList(productSku);
        pd.setProductSkuList(productSkuList);

        return pd;
    }

    /**
     * 查询商品
     *
     * @param skus 商品主键
     * @return 商品
     */
    @Override
    public List<Product> selectProductBySkus(String[] skus)
    {
        return productMapper.selectProductBySkus(skus);
    }

    /**
     * 查询商品Sku
     *
     * @param skuCodes 商品SkuCode主键
     * @return 商品Sku
     */
    @Override
    public List<ProductSku> selectProductSkuBySkuCodes(String[] skuCodes) {
        return productSkuMapper.selectProductSkuBySkuCodes(skuCodes);
    }

    @Override
    public List<ProductDetail> selectProductDetailBySkus(String[] skus) {

        List<ProductDetail> pdList = new ArrayList<>();
        for(String sku : skus){
            //商品表
            Product product = new Product();
            product.setSku(sku);
            List<Product> productList = productMapper.selectProductList(product);
            //商品规格表
            ProductAttribute productAttribute = new ProductAttribute();
            productAttribute.setSku(sku);
            List<ProductAttribute> productAttributeList = productAttributeMapper.selectProductAttributeList(productAttribute);
            //商品sku表
            ProductSku productSku = new ProductSku();
            productSku.setSku(sku);
            List<ProductSku> productSkuList = productSkuMapper.selectProductSkuList(productSku);

            ProductDetail pd = new ProductDetail();
            pd.setProduct(productList.get(0));
            pd.setProductAttributeList(productAttributeList);
            pd.setProductSkuList(productSkuList);

            pdList.add(pd);
        }
        return pdList;
    }

    /**
     * 查询商品列表
     * 
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product)
    {
        return productMapper.selectProductList(product);
    }

    /**
     * 根据关键字，查询商品列表
     *
     * @param key 商品
     * @return 商品集合
     */
    @Override
    public List<Product> queryProductByKey(String key) {
        return productMapper.selectProductByKey(key);
    }

    /**
     * 新增商品
     * 
     * @param pd 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProduct(ProductDetail pd)
    {
        String sku = genSku();

        //商品表
        Product product = pd.getProduct();
        product.setSku(sku);
        product.setSale(0L);
        product.setAuditStatus(AuditStatusType.COMMIT.getStatus());
        product.setAuditRemark("");
        product.setDeleteStatus(0);
        product.setUpdateTime(new Date());
        int number = productMapper.insertProduct(product);

        //商品规格表
        List<ProductAttribute> productAttributeList = pd.getProductAttributeList();
        for(int i = 0 ; i < productAttributeList.size(); i++){
            ProductAttribute attribute = productAttributeList.get(i);
            attribute.setSku(sku);
            attribute.setSort((long) i);
            productAttributeMapper.insertProductAttribute(attribute);
        }

        atomicNum = new AtomicInteger(0);
        //商品sku表
        List<ProductSku> productSkuList = pd.getProductSkuList();
        for(int i = 0 ; i < productSkuList.size(); i++){
            ProductSku productSku = productSkuList.get(i);
            productSku.setSku(sku);
            productSku.setSkuCode(genSkuCode(sku));
            productSku.setTitle(product.getTitle());
            productSku.setSubTitle(product.getSubTitle());
            productSku.setSale(0L);
            productSkuMapper.insertProductSku(productSku);
        }


        return 1;
    }

    /**
     * 生成商品sku
     * @return
     */
    private static String genSku(){
        StringBuilder sb = new StringBuilder();
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS,new Date());
        sb.append(dateStr.substring(2));
        int random = (int) (Math.random()*1000);
        sb.append(random);
        return sb.toString();
    }

    /**
     * 生成商品skuCode
     * @return
     */
    private static String genSkuCode(String sku){
        StringBuilder sb = new StringBuilder();
        sb.append(sku);

        int newNum = atomicNum.incrementAndGet();
        String newStrNum = String.format("%06d",newNum);
        sb.append(newStrNum);

        return sb.toString();
    }

    /**
     * 修改商品
     * 
     * @param pd 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProduct(ProductDetail pd)
    {

        //商品表
        Product product = pd.getProduct();
        product.setAuditStatus(0);
        product.setPublishStatus(0);
        product.setDeleteStatus(0);
        product.setUpdateTime(new Date());
        productMapper.updateProduct(product);


        //商品规格表
        ProductAttribute productAttribute = new ProductAttribute();
        productAttribute.setSku(product.getSku());
        List<ProductAttribute> originalProductAttributeList = productAttributeMapper.selectProductAttributeList(productAttribute);
        //先删除
        int size = originalProductAttributeList.size();
        Long[] ids = new Long[size];
        for(int i = 0; i<size;i++){
            ids[i]= originalProductAttributeList.get(i).getId();
        }
        productAttributeMapper.deleteProductAttributeByIds(ids);
        //再插入
        List<ProductAttribute> productAttributeList = pd.getProductAttributeList();
        for(int i = 0 ; i < productAttributeList.size(); i++){
            ProductAttribute attribute = productAttributeList.get(i);
            attribute.setSku(product.getSku());
            attribute.setSort((long) i);
            productAttributeMapper.insertProductAttribute(attribute);
        }


        //商品sku表
        List<ProductSku> productSkuList = pd.getProductSkuList();
        List<String> spDataList = productSkuList.stream().map(ProductSku::getSpData).collect(Collectors.toList());

        ProductSku productSku = new ProductSku();
        productSku.setSku(product.getSku());
        List<ProductSku> originalProductSkuList = productSkuMapper.selectProductSkuList(productSku);
        List<String> oriSpDataList = originalProductSkuList.stream().map(ProductSku::getSpData).collect(Collectors.toList());
        Map<String,ProductSku> oriSpDataMap = originalProductSkuList.stream().collect(Collectors.toMap(ProductSku::getSpData,ps->ps));
        //skuCode最大值
        List<ProductSku> sortList = originalProductSkuList.stream().sorted(Comparator.comparing(ProductSku::getSkuCode).reversed()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(sortList)){
            atomicNum = new AtomicInteger(0);
        }else {
            String maxSku = sortList.get(0).getSkuCode();
            String code = maxSku.substring(maxSku.length()-6);
            atomicNum = new AtomicInteger(Integer.valueOf(code));
        }

        //删除不存在
        for(ProductSku ori : originalProductSkuList){
            if(!spDataList.contains(ori.getSpData())){
                productSkuMapper.deleteProductSkuById(ori.getId());
            }
        }

        for(ProductSku sku : productSkuList){
            //数据库存在相同的，更新
            if(oriSpDataList.contains(sku.getSpData())){
                ProductSku ps = oriSpDataMap.get(sku.getSpData());
                ps.setTitle(product.getTitle());
                ps.setSubTitle(product.getSubTitle());
                ps.setPic(sku.getPic());
                ps.setPrice(sku.getPrice());
                ps.setResUuid(sku.getResUuid());
                productSkuMapper.updateProductSku(ps);
            }else {
            //数据库不存在相同的，插入
                productSku.setSku(product.getSku());
                productSku.setSkuCode(genSkuCode(product.getSku()));
                productSku.setTitle(product.getTitle());
                productSku.setSubTitle(product.getSubTitle());
                productSku.setPic(sku.getPic());
                productSku.setPrice(sku.getPrice());
                productSku.setSpData(sku.getSpData());
                productSku.setResUuid(sku.getResUuid());
                productSku.setSale(0L);
                productSkuMapper.insertProductSku(productSku);
            }
        }

        //店铺商品数量减一
        Shop shop= shopMapper.selectShopById(product.getShopId());
        shop.setProductCount(shop.getProductCount()-1);
        shopMapper.updateShop(shop);
        return 1;
    }

    /**
     * 提交商品
     *
     * @param pd 商品
     * @return 结果
     */
    @Override
    public int commitProduct(Product pd) {
        Product product = new Product();
        product.setSku(pd.getSku());
        List<Product> productList = productMapper.selectProductList(product);

        product = productList.get(0);
        //如果是未提交，这更改为待审核
        if(AuditStatusType.COMMIT.getStatus().equals(product.getAuditStatus())){
            product.setAuditStatus(AuditStatusType.AUDIT.getStatus());
            product.setAuditRemark("");
            product.setUpdateTime(new Date());
            return productMapper.updateProduct(product);
        }
        return 0;
    }

    /**
     * 审核商品
     *
     * @param pd 商品
     * @return 结果
     */
    @Override
    public int auditProduct(Product pd) {
        Product product = new Product();
        product.setSku(pd.getSku());
        List<Product> productList = productMapper.selectProductList(product);

        product = productList.get(0);
        product.setAuditStatus(pd.getAuditStatus());
        product.setAuditRemark(pd.getAuditRemark());
        product.setUpdateTime(new Date());
        return productMapper.updateProduct(product);
    }

    /**
     * 上下架商品
     *
     * @param pd 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publishProduct(Product pd) {
        Product product = new Product();
        product.setSku(pd.getSku());
        List<Product> productList = productMapper.selectProductList(product);

        product = productList.get(0);
        Shop shop= shopMapper.selectShopById(product.getShopId());
        if(!AuditStatusType.SUCCESS.getStatus().equals(product.getAuditStatus())){
            return 0;
        }
        if(pd.getPublishStatus()!=null && pd.getPublishStatus().equals(Constants.PUBLISH_STATUS_UP)){
            product.setPublishStatus(Constants.PUBLISH_STATUS_UP);
            //店铺商品数量加一
            shop.setProductCount(shop.getProductCount()+1);
            shopMapper.updateShop(shop);
        }else {
            product.setPublishStatus(Constants.PUBLISH_STATUS_DOWN);
            //店铺商品数量减一
            shop.setProductCount(shop.getProductCount()-1);
            shopMapper.updateShop(shop);
        }
        product.setPublishTime(new Date());
        product.setUpdateTime(new Date());
        return productMapper.updateProduct(product);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(Long[] ids)
    {
        for(Long id : ids){
            Product product = productMapper.selectProductById(id);
            if(Constants.PUBLISH_STATUS_UP.equals(product.getPublishStatus())){
                throw new BaseException("上架状态不允许删除");
            }
        }
        return productMapper.deleteProductByIds(ids);
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteProductById(Long id)
    {
        return productMapper.deleteProductById(id);
    }
}
